package com.songcha.module_main.ui.fragment.qmy

import android.os.Bundle
import android.view.View
import com.songcha.library_base.mvvm.base.BaseMvvmFragment
import com.songcha.library_business.bean.advert.AdvertInfoBean
import com.songcha.library_business.config.FunctionConfig
import com.songcha.library_business.config.VarConfig
import com.songcha.library_business.helper.AdvertCoverHelper
import com.songcha.library_business.helper.AdvertHelper
import com.songcha.library_business.helper.UMengHelper
import com.songcha.library_common.ui.view.BottomNavigationView
import com.songcha.library_common.util.LogUtil
import com.songcha.library_common.util.ToastUtil
import com.songcha.module_main.databinding.MainFragQmyBinding
import com.songcha.module_main.R
import com.songcha.module_main.ui.dialog.AutoStrikeRewardDialog
import com.songcha.module_main.ui.dialog.QmyAchievementDialog
import com.songcha.module_main.ui.view.WoodenFishView
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit

class QmyFragment:BaseMvvmFragment<QmyViewModel,MainFragQmyBinding>(), View.OnClickListener,WoodenFishView.IStrikeWoodenFishListener,BottomNavigationView.IOnBottomNavigationItemChangeListener {
    private var mLastGongDe = 0
    private var mLastPostTime = 0L
    private var mAutoStrikeDispose: Disposable? = null
    private var mBannerAdvertDispose: Disposable? = null
    private var mIsRewardAdvertLoadSuccess = false

    init {
        TAG = QmyFragment::class.java.simpleName
    }

    companion object{
        const val AUTO_STRIKE_INTERVAL = 500L
    }

    override fun getLayoutId(): Int {
        return R.layout.main_frag_qmy
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        databinding.mainViewStrike.setOnClickListener(this)
        databinding.mainIvMusic.setOnClickListener(this)
        databinding.mainWfv.setStrikeWoodenFishListener(this)
        databinding.mainIvAutoStrike.setOnClickListener(this)

        initAdvert()
    }

    override fun onResume() {
        super.onResume()
    }

    private fun initAdvert(){
        AdvertCoverHelper.loadAdvertByCover(requireActivity(),AdvertHelper.ADVERT_TYPE_INSERT_SCREEN,VarConfig.ADVERT_HOME_INSERT_SCREEN_INFO,
            null,0f,object:AdvertHelper.ILoadAdvertCommonListener{
                override fun onSuccess(type: Int, height: Int, view: View?) {

                }

                override fun onError(type: Int, code: Int, msg: String) {

                }

                override fun onClose(type: Int) {

                }

            })
    }

    override fun initObserver() {
        viewModel.recordBean.observe(this){data ->
            if(data == null) return@observe
            //TODO
            databinding.mainTvTodayGongde.text = data.todayMeritsVirtues.toString()
            databinding.mainTvTotalGongde.text = data.totalMeritsVirtues.toString()
            databinding.mainTvMaxContinuousStrike.text = data.highestHit.toString()
            //databinding.memoTvRank.text = "总榜排行：" + data.ranking.toString()
        }

        viewModel.medalList.observe(this){data->
            if(data.isEmpty()) return@observe
            for(item in data){
                val desc = when(item.type){
                    1 -> "完成${item.myCondition}次连击"
                    2 -> "累计获取${item.myCondition}功德"
                    3 -> "累计敲木鱼${item.myCondition}天"
                    4 -> "进入日榜前${item.myCondition}"
                    else -> ""
                }
                val dialog = QmyAchievementDialog(requireActivity(),item.headline,desc,item.logoBright)
                dialog.show()
            }
        }
    }

    override fun onGetData() {
        //viewModel.getCalendarTaskRecord()
        viewModel.getWoodenFishRecord()
    }

    private fun isAutoStriking():Boolean{
        return (mAutoStrikeDispose != null && !mAutoStrikeDispose!!.isDisposed)
    }

    private fun startAutoStrike(){
        if(isAutoStriking()) return
        databinding.mainIvAutoStrike.setImageResource(R.mipmap.main_icon_qmy_auto_enabled)
        startLoadBannerAdvert()
        mAutoStrikeDispose = Observable.interval(0,AUTO_STRIKE_INTERVAL,TimeUnit.MILLISECONDS)
            .subscribeOn(Schedulers.computation())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe{it->
                databinding.mainWfv.strikeWoodenFish()
            }
    }

    private fun stopAutoStrike(){
        mAutoStrikeDispose?.dispose()
        stopLoadBannerAdvert()
        databinding.mainIvAutoStrike.setImageResource(R.mipmap.main_icon_qmy_auto_disenabled)
    }

    private fun startLoadBannerAdvert(){
        if(!FunctionConfig.IS_ADVERT_ENABLED || VarConfig.ADVERT_HOME_BANNER_AUTO_QMY.type == AdvertInfoBean.ADVERT_TYPE_DIS_ENABLED) return
        stopLoadBannerAdvert()
        mBannerAdvertDispose = Observable.interval(0,60,TimeUnit.SECONDS)
            .subscribeOn(Schedulers.computation())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe{it->
                loadBannerAdvert()
            }
    }

    private fun stopLoadBannerAdvert(){
        mBannerAdvertDispose?.dispose()
    }

    private fun loadBannerAdvert(){
        AdvertCoverHelper.loadAdvertByCoverBanner(requireActivity(),VarConfig.ADVERT_HOME_BANNER_AUTO_QMY,
            databinding.mineFlAdvertBanner,20f)
    }

    private fun loadRewardAdvert(){
        mIsRewardAdvertLoadSuccess = false
        AdvertCoverHelper.loadAdvertByCover(requireActivity(),AdvertHelper.ADVERT_TYPE_REWARD,VarConfig.ADVERT_HOME_REWARD_AUTO_QMY,
            null,0f,object :AdvertHelper.ILoadAdvertCommonListener{
                override fun onSuccess(type: Int, height: Int, view: View?) {
                    mIsRewardAdvertLoadSuccess = true
                }

                override fun onError(type: Int, code: Int, msg: String) {
                    databinding.mainIvAutoStrike.setImageResource(R.mipmap.main_icon_qmy_auto_disenabled)
                    ToastUtil.show("加载视频广告失败")
                }

                override fun onClose(type: Int) {
                    if(!mIsRewardAdvertLoadSuccess)
                        databinding.mainIvAutoStrike.setImageResource(R.mipmap.main_icon_qmy_auto_disenabled)
                    else
                        startAutoStrike()
                }

            })
    }

    override fun onStrikeWoodenFishStar(continuousStrikeCount: Int,isContinueStrike:Boolean) {
        /*if(continuousStrikeCount > 3){
            if(!databinding.memoSvga.isAnimating)
                databinding.memoSvga.startAnimation()
        }*/

        if(!isContinueStrike)
            mLastGongDe = 0

        viewModel.addFakeGongDe(1,continuousStrikeCount)
    }

    override fun onStrikeWoodenFishEnd(continuousStrikeCount: Int,isContinueStrike:Boolean) {
        //databinding.memoSvga.stopAnimation()

        var count = continuousStrikeCount

        if(continuousStrikeCount > 1){
            if(isContinueStrike){
                count -= mLastGongDe
                mLastGongDe = continuousStrikeCount
                //LogUtil.log("aaa",count,tag = "onStrikeWoodenFishEnd")
            }else{
                mLastGongDe = continuousStrikeCount
                //LogUtil.log("bbb",count,tag = "onStrikeWoodenFishEnd")
            }
            mLastPostTime = System.currentTimeMillis()
        }else{
            mLastGongDe = continuousStrikeCount
        }

        //LogUtil.log("post:" + count,tag = "onStrikeWoodenFishEnd")

        if(count <= 0) return

        //UMengHelper.onUMEvent(this@StrikeWoodenFishActivity,"qmy_start_strike")
        viewModel.addGongDe(count)

        if(viewModel.recordBean.value!= null && continuousStrikeCount > viewModel.realMaxStrikeCount)
            viewModel.setMaxStrike(continuousStrikeCount)

    }

    override fun onClick(v: View) {
        when(v.id){
            R.id.main_view_strike->{
                if(isAutoStriking()) return
                databinding.mainWfv.strikeWoodenFish()
            }
            R.id.main_iv_music->{
                databinding.mainWfv.isStrikeVoiceEnabled = !databinding.mainWfv.isStrikeVoiceEnabled
                databinding.mainIvMusic.setImageResource(if(databinding.mainWfv.isStrikeVoiceEnabled) R.mipmap.main_icon_qmy_music else R.mipmap.main_icon_qmy_music_close)
            }
            R.id.main_iv_auto_strike->{
                val isAuto = isAutoStriking()
                databinding.mainIvAutoStrike.setImageResource(if(isAuto) R.mipmap.main_icon_qmy_auto_disenabled else R.mipmap.main_icon_qmy_auto_enabled)
                if(isAuto){
                    stopAutoStrike()
                } else{
                    if(FunctionConfig.IS_ADVERT_ENABLED && VarConfig.ADVERT_HOME_REWARD_AUTO_QMY.type != VarConfig.ADVERT_TYPE_DIS_ENABLED){
                        val dialog = AutoStrikeRewardDialog(v.context,{
                            //startAutoStrike()
                            loadRewardAdvert()
                        },{
                            databinding.mainIvAutoStrike.setImageResource(R.mipmap.main_icon_qmy_auto_disenabled)
                        })
                        dialog.show()
                    }else{
                        startAutoStrike()
                    }
                }
            }
        }
    }

    override fun onStop() {
        super.onStop()
        stopAutoStrike()
    }

    override fun onBottomNavigationItemChange(position: Int, tag: String) {
        if(tag == TAG){
            //viewModel.getCalendarTaskRecord()
        }else{
            stopAutoStrike()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mAutoStrikeDispose?.dispose()
        mBannerAdvertDispose?.dispose()
    }


}